<?php

namespace utils\tools;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use think\facade\Log;

class MailService
{
    protected $mailer;

    public function __construct()
    {
        $config = config('mail');

        $this->mailer = new PHPMailer(true);
        $this->mailer->isSMTP();
        $this->mailer->Host       = $config['host'];
        $this->mailer->SMTPAuth   = true;
        $this->mailer->Username   = $config['username'];
        $this->mailer->Password   = $config['password'];
        $this->mailer->SMTPSecure = $config['encryption'];
        $this->mailer->Port       = $config['port'];
        $this->mailer->setFrom($config['from_email'], $config['from_name']);
        $this->mailer->CharSet = 'UTF-8';
        // $this->mailer->SMTPDebug = 4;
    }

    public function send($toEmail, $toName, $subject, $body, $altBody = '')
    {
        try {
            $this->mailer->addAddress($toEmail, $toName);
            $this->mailer->isHTML(true);
            $this->mailer->Subject = $subject;
            $this->mailer->Body    = $body;
            $this->mailer->AltBody = $altBody;

            $this->mailer->send();
            return true;
        } catch (Exception $e) {
            Log::record($e->getMessage());
            Log::record("邮件发送失败: {$this->mailer->ErrorInfo}",'error');
            return false;
        }
    }
}
